package main

import (
	"database/sql"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"time"
)

type Product struct {
	gorm.Model
	Code     string
	Price    sql.NullInt32
	Birthday *time.Time
}

//type User struct {
//	Id   int32 `gorm:"column:idd;primaryKey;index:name;comment:test;default:x"`
//	Name string
//}

// `User` 属于 `Company`，`CompanyID` 是外键
type User struct {
	gorm.Model
	Name      string
	CompanyID int
	Company   Company
}

type Company struct {
	ID   int
	Name string
}

type NewUser struct {
	gorm.Model
	MemberNumber string
	CreditCards  []CreditCard `gorm:"foreignKey:UserNumber;references:UserNumber"`
}

type CreditCard struct {
	gorm.Model
	Number     string
	UserNumber string
	NewUser    NewUser
}

func (CreditCard) TableName() string {
	return "dfsaf"
}

func main() {

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level
			IgnoreRecordNotFoundError: true,        // Ignore ErrRecordNotFound error for logger
			ParameterizedQueries:      true,        // Don't include params in the SQL log
			Colorful:                  true,        // Disable color
		},
	)

	dsn := "root:123456@tcp(127.0.0.1:3306)/go-shop?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{TablePrefix: "pb"},
		Logger:         newLogger,
	})
	if err != nil {
		panic("failed to connect database")
	}

	//db.CreateInBatches()
	db.AutoMigrate(&CreditCard{}, &NewUser{})

	return
	//db.Create(&User{
	//	Name: "Jinzhu",
	//	Company: Company{
	//		Name: "小郑",
	//	},
	//})
	var u User
	db.Preload("Company").First(&u)
	db.Joins("Company").First(&u)
	fmt.Println(u.Name, u.Company.Name)
	//db.Create(&Product{Code: "D42", Price: 100})

	// Read
	var product Product
	db.First(&product)

	//res := db.First(&product, []int{1, 2, 3}) // 根据整型主键查找
	//res := db.Where(&Product{Price: sql.NullInt32{1, true}}).Find(&product) // 根据整型主键查找
	//fmt.Println(product)
	//fmt.Println(res.RowsAffected)
	//db.First(&product, "code = ?", "D42") // 查

	//db.Model(&Product{}).Update()
	//db.Model(&product).Where("id", 1).Update("Price", 0)
	//db.Model(&product).Where("id", 1).Updates(Product{Price: 0})

}
